package cn.com.netedge.iot.frontend.datasave;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

import cn.com.netedge.iot.common.constants.CacheKeyConstants;
import cn.com.netedge.iot.common.utils.ChronicleQueueUtil;
import cn.com.netedge.iot.common.utils.DateUtil;
import cn.com.netedge.iot.common.utils.FrontEndUtil;
import cn.com.netedge.iot.common.utils.RedisUtil;
import cn.com.netedge.iot.common.utils.StringUtil;
import cn.com.netedge.iot.frontend.datasave.config.DataSaveConfig;
import cn.com.netedge.iot.frontend.datasave.utils.JmsMsgUtil;

@SpringBootApplication(exclude = {RedisAutoConfiguration.class})
@ComponentScan(basePackages = {"cn.com.netedge.iot.fe.datasave","cn.com.netedge.iot.common.utils"})
@EnableScheduling
public class FeDataSaveApplication {
    private static Logger logger = LoggerFactory.getLogger(FeDataSaveApplication.class);

    public static void main(String[] args) {
        logger.debug("Starting application with args: {}", args);
        ApplicationContext context = SpringApplication.run(FeDataSaveApplication.class, args);
        DataSaveConfig.appContext = context;

        initApp();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.debug("Detected shutdown, cleaning up...");
            ChronicleQueueUtil.close();
        }));

    }

    public static void initApp() {
        FrontEndUtil frontEndUtil = DataSaveConfig.appContext.getBean(FrontEndUtil.class);
        DataSaveConfig.setMachineName(CacheKeyConstants.KEY_FRONTEND_DATA_SAVE_MACHINE + frontEndUtil.getMachineNo());
        Date now = new Date();
        RedisUtil.hset(CacheKeyConstants.KEY_FRONTEND_DATA_SAVE_MACHINE + "machine_map", DataSaveConfig.getMachineName(), DateUtil.DateToLongStr(now));

        JmsMsgUtil jmsMsgUtil = DataSaveConfig.appContext.getBean(JmsMsgUtil.class);
        jmsMsgUtil.subscribeQueues();

        String configPath = System.getProperty("configPath");
        logger.info("configPath:{}", configPath);
        if (StringUtil.isEmpty(configPath)) {//云平台
            logger.info("进入 云平台模式");

            return;
        }
        logger.info("进入 本地版模式");
        DataSaveConfig.setLocalMode(true);
    }

}
